package com.zx._08_网络.cpt2_Multicast;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.util.Scanner;

public class MulticastSocketTest implements Runnable {

    // 多点广播ip
    public static final String BROADCAST_IP = "230.0.0.1";
    // 多点广播端口
    private static final int BROADCAST_PORT = 30000;
    // 指定接受数据报的字节数组
    private static final int DATA_LEN = 4096;
    // 指定接受数据报的字节数组
    byte[] inBuff = new byte[DATA_LEN];
    private MulticastSocket socket = null;
    private InetAddress broadcastAddress = null;
    // 定义一个用于接收数据报的DatagramPacket对象， 设置它的数据报的字节数组和大小
    private DatagramPacket inPacket = new DatagramPacket(inBuff, inBuff.length);
    // 定义一个用于发送数据报的DatagramPacket
    private DatagramPacket outPacket;

    public static void main(String[] args) {
        new MulticastSocketTest().init();
    }

    @Override
    public void run() {
        try {
            while (true) {
                this.socket.receive(this.inPacket);
                System.out.println(new String(this.inPacket.getData()));
            }
        } catch (IOException e) {
            e.printStackTrace();
            if (this.socket != null) {
                try {
                    if (this.socket != null) {
                        this.socket.leaveGroup(this.broadcastAddress);
                        this.socket.close();
                    }
                    System.exit(1);
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }

        }
    }

    public void init() {
        try {
            // 用来键盘输入
            Scanner scan = new Scanner(System.in);
            // 创建MulticastSocket，并绑定端口
            this.socket = new MulticastSocket(BROADCAST_PORT);
            // 创建本地ip对象
            this.broadcastAddress = InetAddress.getByName(BROADCAST_IP);
            // 该ip对象加入MulticastSocket组
            this.socket.joinGroup(broadcastAddress);
            // 设置播放范围
            this.socket.setTimeToLive(1);
            // 设置本MulticastSocket组发送的数据报都会被会送到本身。
            this.socket.setLoopbackMode(false);

            this.outPacket = new DatagramPacket(new byte[0], 0, InetAddress.getByName(BROADCAST_IP), BROADCAST_PORT);

            new Thread(this).start();// 启动一个客户端，接受数据

            while (scan.hasNextLine()) {
                byte[] buf = scan.nextLine().getBytes();
                this.outPacket.setData(buf);
                this.socket.send(outPacket);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            this.socket.close();
        }
    }
}
